#
#	El manager v.0.01 - Derivart (http://www.derivart.info)
#	@Coded: Mar Cane / Martin Nadal (2009)
#
import errno
import os, shutil
from BeautifulSoup import BeautifulSoup
from urllib2 import Request, urlopen, URLError, HTTPError
import urllib
import urllib2
import time
import sys

class webcrawlerSGAEChecker():
    def __init__(self):
        self.urlSGAE = "https://socios.sgae.es/RepertorioSgae/Buscar.aspx?opcion=buscar"

    def chechSong(self,song,singer):
        values = {'strCreatorName':singer,'pageSize':'10', 'strNameWork':song,'AcceptDisclaimer' : 'SI','currentPage':1,'selISWC':'','selStrNameWork':'','selAlfaObras':'','selStrCreatorName':'','detStrNameWork':'' }
        data = urllib.urlencode(values)
        print self.urlSGAE
        req = urllib2.Request(self.urlSGAE, data)
        try:
            response = urllib2.urlopen(req)
        except HTTPError, e:
            print 'The server couldn\'t fulfill the request.'
            print 'Error code: ', e.code
        except URLError, e:
            print 'We failed to reach a server.'
            print 'Reason: ', e.reason
        else:
            # everything is fine
            sgaePage = response.read()
            #MARTIN:pillo la excepcion por si ocurre (que aveces ocurre) no se quede el hilo pillao y podemos finalizar 
            try:
                soup = BeautifulSoup(sgaePage)
            except:
                return False
                
            tableResults = soup.find("table",{"id": "tblSearchResult"})
            tr = BeautifulSoup(str(tableResults))
            trResult = tr.findAll("tr")
            totalTR = len(trResult)
            #print(totalTR)
            i=0 
            for td in trResult:
               tdResults = td.findAll("td")
               if len(tdResults)>3:
                    if i>3:	
                         titleSgae = str(tdResults[3].contents[0])[19:-19].lower()	
                         singerSgae = str(tdResults[12].contents[0])[19:-19].lower()
                         #print title.lower()+" "+titleSgae+" @ "+singer.lower()+" "+singerSgae
                         if song.lower() == titleSgae and singer.lower() == singerSgae:
                            return True
               i = i+ 1
        return False

